///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
//////////												//////////
//////////					Money system:					//////////
//////////			Created by: [TG] Chief (Alex) [TGR]				//////////
//////////			Youtube page:	www.youtube.com/humblesnurp		//////////
//////////												//////////
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
//////////												//////////
//////////			You may use/edit this script for ANYTHING!			//////////
//////////					ITS LICENCE FREE				//////////
//////////												//////////
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
//include( '../client/cl_init.lua' )
AddCSLuaFile( "autorun/client/cl_init.lua" )
AddCSLuaFile( "base/CostSettings.lua" )

Msg("Money system - Server Activated\n")
resource.AddFile("models/GTA IV/money_1.mdl")
resource.AddFile("models/GTA IV/money_2.mdl")
resource.AddFile("models/GTA IV/money_3.mdl")
resource.AddFile("models/GTA IV/money_4.mdl")
resource.AddFile("models/GTA IV/money_pallet.mdl")
Msg("Money system - Resources added...\n")
function AddResourceDir(dir) // recursively adds everything in a directory to be downloaded by client
	local list = file.FindDir("../"..dir.."/*")
	for _, fdir in pairs(list) do
		if fdir != ".svn" then // don't spam people with useless .svn folders
			AddResourceDir(dir.."/"..fdir)
		end
	end
 
	for k,v in pairs(file.Find("../"..dir.."/*")) do
		resource.AddFile(dir.."/"..v)
	end
end
AddResourceDir("materials/Models/Jason278")

include("base/CostSettings.lua")
include("base/GroundMinerals.lua")
CreateConVar("ms_payday_amount", 5, FCVAR_NOTIFY | FCVAR_ARCHIVE | FCVAR_GAMEDLL)
CreateConVar("ms_payday_interval", 8, FCVAR_NOTIFY | FCVAR_ARCHIVE | FCVAR_GAMEDLL)
CreateConVar("ms_paydays", 1, FCVAR_NOTIFY | FCVAR_ARCHIVE | FCVAR_GAMEDLL)
CreateConVar("ms_startcash", 0, FCVAR_NOTIFY | FCVAR_ARCHIVE | FCVAR_GAMEDLL)
CreateConVar("ms_active", 1, FCVAR_NOTIFY | FCVAR_ARCHIVE | FCVAR_GAMEDLL)


MoneyCFG = {}

MoneyCFG.STARTMONEY = 15 -- This is the amount of cash that players start with
MoneyCFG.PAYDAYS = true -- Should there be paydays? 	true = yes, 	false = no
MoneyCFG.PAYDAY_AMOUNT = 5 -- If there are paydays, what should the salary be?
MoneyCFG.PAYDAY_INTERVAL = 8 -- If there are paydays, what should the payday interval be? (Seconds)
MoneyCFG.PAYDAY_SOUND = false -- If there are paydays, should a sound play when there's a payday?  true = yes, 	false = no
MoneyCFG.MONEY_HUD = true -- Should the money be displayed on the screen? true = yes, false = no
MoneyCFG.HasSeller = false
--MoneyCFG.MONEY_ACTIVE = true


local function funcCallback_ms(CVar, PreviousValue, NewValue)
	if (CVar == "ms_payday_amount") then
		MoneyCFG.PAYDAY_AMOUNT = tonumber(NewValue)
	elseif (CVar == "ms_payday_interval") then
		MoneyCFG.PAYDAY_INTERVAL = tonumber(NewValue)
		timer.Adjust("payday_timer",tonumber(NewValue),0)
	elseif (CVar == "ms_paydays") then
		MoneyCFG.PAYDAYS = tonumber(NewValue)
	elseif (CVar == "ms_active") then
		if (tonumber(NewValue) > 0) then
			MoneyCFG.MONEY_ACTIVE = true
		else
			MoneyCFG.MONEY_ACTIVE = false
		end
		umsg.Start("ms_active")
			umsg.Bool(MoneyCFG.MONEY_ACTIVE)
		umsg.End()
	end
end
cvars.AddChangeCallback("ms_payday_amount", funcCallback_ms)
cvars.AddChangeCallback("ms_payday_interval", funcCallback_ms)
cvars.AddChangeCallback("ms_paydays", funcCallback_ms)
cvars.AddChangeCallback("ms_startcash", funcCallback_ms)
cvars.AddChangeCallback("ms_active", funcCallback_ms)

MoneyCFG.PAYDAYS = tonumber(GetConVar("ms_paydays"):GetInt())
MoneyCFG.PAYDAY_INTERVAL = tonumber(GetConVar("ms_payday_interval"):GetInt())
MoneyCFG.PAYDAY_AMOUNT = tonumber(GetConVar("ms_payday_amount"):GetInt())
if (tonumber(GetConVar("ms_active"):GetInt()) > 0) then
	MoneyCFG.MONEY_ACTIVE = true
else
	MoneyCFG.MONEY_ACTIVE = false
end

//**********************************************************************
//********************** CREATE PLAYER METHODS *************************
//**********************************************************************
local pm = FindMetaTable("Player") -- We state that entities under the meta table "player" is called pm, just to make it easier!

function PlayerMoneySpawn( ply )
	ply:Money_Create()
	umsg.Start("ms_active")
		umsg.Bool(MoneyCFG.MONEY_ACTIVE)
	umsg.End()
end
hook.Add("PlayerInitialSpawn", "MoneySystemStart", PlayerMoneySpawn)

function pm:Money_Create() -- DONT TOUCH! THIS FUNCTION SAVES THE SHIT
	print("Creating money account for: "..self:Nick())
	if self:GetPData( "cash" ) == nil then -- if there is no data under "cash", create some!
		self:SetPData( "cash", MoneyCFG.STARTMONEY ) -- if there is no "cash" data, give them 15 cash to begin with!
	end
	self:SetNWInt( "cash", self:GetPData( "cash" ) ) -- Sends the amount to the players' screens
	if ( tonumber(GetConVar("ms_startcash"):GetInt()) > 0 ) then
		self:Money_Set( tonumber(GetConVar("ms_startcash"):GetInt()) )
	end
end

function pm:Money_Set( cash ) -- player:Money_Set = SET THE MONEY OF A PLAYER
	self:SetPData( "cash", tonumber(cash) ) -- Saves the cash to the server
	self:SetNWInt( "cash", tonumber(cash) ) -- Sends the amount to the players' screens
end

function pm:Money_Add( cash ) -- player:Money_Add = ADD MONEY FOR A PLAYER
	if (cash > 0) then -- If the cash to give is over 0...
		local current = tonumber(self:GetPData( "cash" )) -- Get the old amount of money
		-- print( self:Nick().."'s UniqueID is: "..self:UniqueID())
		-- print( self:Nick().."'s UserID is: "..self:UserID())
		if (current == nil) then
			self:Money_Set( cash )
		else
			self:Money_Set( current + cash )
		end
		 -- Set the money to: The old amount of money + the money wished to be added
	end
end

function pm:Money_Has( cash ) -- player:Money_Add = GET THE MONEY FOR A PLAYER
	local current = tonumber(self:GetPData( "cash" )) -- Get the old amount of money
	if current >= tonumber(cash) then -- if the old amount si over the amount checked...
		return true -- say it's true!
	else
		return false -- if not, say it's false!
	end
end

function pm:Money_Get() -- player:Money_Add = GET THE MONEY FOR A PLAYER
	local current = tonumber(self:GetPData( "cash" )) -- Get the old amount of money
	return current
end

function pm:Money_Take( cash )  -- player:Money_Add = TAKE MONEY FOR A PLAYER
	if self:Money_Has( cash ) then -- if you got the amount of money...
		local current = tonumber(self:GetPData( "cash" )) -- Get the old amount of money
		self:Money_Set( current - cash ) -- Take the old amount of money and take away the amount given!
	end
end

//**********************************************************************
//********************** HOOKS AND OTHER       *************************
//**********************************************************************



--print("Try to create: "..tonumber(MoneyCFG.PAYDAY_INTERVAL).." timer")
timer.Create( "payday_timer", tonumber(MoneyCFG.PAYDAY_INTERVAL), 0, function()
	--print("one with: "..MoneyCFG.PAYDAYS)
	if (MoneyCFG.PAYDAYS != 0 && MoneyCFG.MONEY_ACTIVE) then
		--print("two")
		for k, ply in pairs(player.GetAll()) do
			ply:Money_Add( MoneyCFG.PAYDAY_AMOUNT )
			if MoneyCFG.PAYDAY_SOUND then
				ply:EmitSound("items/ammo_pickup.wav")
			end
		end
	end
end	)

timer.Create( "price_change", 1, 0, function()
	--print("one with: "..MoneyCFG.PAYDAYS)
	if (MoneyCFG.MONEY_ACTIVE) then
		--local prtstr = ""
		local SM = CAF.GetAddon("Selling Machine")
		for k, v in pairs(SM.resources) do
			--prtstr = ""
			if (math.random(0,100) < 70) then
				--prtstr = prtstr .. "T.from: " .. SM.resources[k].trend
				SM.resources[k].trend = SM.FetchRandomTrend(SM.resources[k].trend)
				--prtstr = prtstr .. " -> " .. SM.resources[k].trend
				if (SM.resources[k].trend == "dwn") then
					--prtstr = prtstr .. " m: " .. SM.resources[k].marked
					SM.resources[k].marked = SM.resources[k].marked - math.random(1,10)
					if (SM.resources[k].marked < 50) then SM.resources[k].marked = 50 end
					--prtstr = prtstr .. " -> " .. SM.resources[k].marked
				elseif (SM.resources[k].trend == "gup") then
					--prtstr = prtstr .. " m: " .. SM.resources[k].marked
					SM.resources[k].marked = SM.resources[k].marked + math.random(1,10)
					if (SM.resources[k].marked > 150) then SM.resources[k].marked = 150 end
					--prtstr = prtstr .. " -> " .. SM.resources[k].marked
				else
					--prtstr = prtstr .. " m: " .. SM.resources[k].marked
				end
			end
			--MsgN(prtstr.." p: "..tostring(SM.resources[k].value * (SM.resources[k].marked/100)))
		end
		timer.Adjust( "price_change", math.random(120,600), 0)
	end
end	)

concommand.Add( "Spwn_Mny", function( ply, cmd, args )
	if (args[1]) then
		local tr = ply:GetEyeTraceNoCursor()
		local SpawnPos = tr.StartPos + (tr.Normal*40)
		local needcash = tonumber(args[1])
		if ply:Money_Has(needcash) then
			ply:Money_Take(needcash)
			/*umsg.Start("HintMessages", ply)
				umsg.Short( NOTIFY_GENERIC )
				umsg.String( "Spawned "..needcash.." credits" )
			umsg.End()*/
			ply:EmitSound("buttons/button17.wav",100,100)
			ply:SendLua("GAMEMODE:AddNotify(\"Spawned "..needcash.." credits\", NOTIFY_GENERIC, 3)")
		else
			/*umsg.Start("HintMessages", ply)
				umsg.Short( NOTIFY_ERROR )
				umsg.String( "Need "..needcash.." credits" )
			umsg.End()*/
			ply:EmitSound("buttons/button10.wav",100,100)
			ply:SendLua("GAMEMODE:AddNotify(\"Need "..needcash.." credits\", NOTIFY_ERROR, 3)")
			return
		end
		ent = ents.Create('ams_money')
		--if !ent:IsValid() then return false end
		ent:SetPos(SpawnPos)
		ent.value = needcash
		ent:Spawn() --run ENT:Initialize()
		ent:Activate()
		local phys = ent:GetPhysicsObject()
		if phys:IsValid() then
			phys:SetMaterial( "paper" )
			phys:AddVelocity( tr.Normal*150 )
		end
	end
end )

function MoneyProp(ply, model)
	if (MoneyCFG.MONEY_ACTIVE) then
		local prop=ents.Create("prop_physics")
		prop:SetModel(model)
		--prop:SetPos(Vector(0,0,0))
		prop:Spawn()
		
		local phys=prop:GetPhysicsObject()
		prop:Remove()
		if phys:IsValid() then
			ply:PrintMessage(HUD_PRINTTALK,	"Phys Valid")
			ply:PrintMessage(HUD_PRINTTALK,	"PhysVolume: "..phys:GetVolume())
			ply:PrintMessage(HUD_PRINTTALK,	"PhysMass: "..phys:GetMass())
		else
			ply:PrintMessage(HUD_PRINTTALK,	"Phys Invalid")
		end
		
		local PropPrice = GetPropPrice(phys:GetVolume(), phys:GetMass())
		
		if ply:Money_Has(PropPrice) then
			ply:PrintMessage(HUD_PRINTTALK,	"Deducted "..PropPrice.." credits")
			ply:Money_Take(PropPrice)
			return true
		else
			ply:PrintMessage(HUD_PRINTTALK,	"Need "..PropPrice.." credits")
			return false
		end
		return false
	else
		return true
	end
end
hook.Add( "PlayerSpawnProp", "MoneyProp", MoneyProp )


 function thousandpointers(amount)
  local formatted = amount
  while true do  
    formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1\.%2')
    if (k==0) then
      break
    end
  end
  return formatted
end